import { GraphQLScalarType, GraphQLError } from 'graphql';
import { Kind } from 'graphql/language';

export const MongoQueryScalar = new GraphQLScalarType({
    name: 'MongoQueryScalar',
    description: 'Json字符串转换为对象',
    parseValue(value: string) {
        console.log('MongoQueryScalar', value);
        if (typeof value === 'string' && value.trim() !== '') {
            const json = JSON.parse(value);
            return json;
        } else if (typeof value === 'object' && value !== null) {
            return value;
        } else {
            return {}
        }
    },
    serialize(value) {
        return value;
    },
    parseLiteral(ast) {
        if (ast.kind !== Kind.STRING) {
            throw new GraphQLError(
                `Query error: Can only parse dates strings, got a: ${ast.kind}`,
                [ast],
            );
        }
        try {
            if (ast.value === null || ast.value.trim() === '') {
                return {};
            } else if (typeof ast.value === 'object' && ast.value !== null) {
                return ast.value;
            }
            const json = JSON.parse(ast.value);
            return json;
        } catch {
            return ast.value;
        }
    },
});